package com.lq.rocketmq.base.producer;

import com.lq.rocketmq.config.MyConstant;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.concurrent.TimeUnit;

/**
 * @program: myrocketmq
 * @description: 发送异步消息
 * @author: LQ
 * @create: 2021-05-07 22:38
 */

public class AsyncProducer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        //1.创建消息生产者producer,并制定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer(MyConstant.MSG_GROUP);
        //2.指定Nameserver地址
        producer.setNamesrvAddr(MyConstant.NAMESRV_ADDR);
        //3.启动producer
        producer.start();
        //4.创建消息对象,指定主体Topic,Tag和消息体
        for (int i = 0; i < MyConstant.MSG_COUNT; i++) {
            // 循环发送10条数据
            /*
             * 需要三个参数
             * 参数一:消息主题Topic
             * 参数二:消息Tag
             * 参数三:消息内容
             */
            Message msg = new Message(MyConstant.TOPIC, MyConstant.TAG1, ("Hello World" + i).getBytes());
            //5.异步发送消息
            producer.send(msg, new SendCallback() {
                /**
                 * 发送成功回调函数
                 * @param sendResult
                 */
                @Override
                public void onSuccess(SendResult sendResult) {
                    // 成功回调函数
                    System.out.println("发送结果:" + sendResult);
                }

                /**
                 * 发送异常回调函数
                 * @param e
                 */
                @Override
                public void onException(Throwable e) {
                    // 失败回调函数
                    System.err.println("发送异常:" + e);
                }
            });
            // 线程睡1秒,虚拟机质量不怎么样,需要延时
            TimeUnit.SECONDS.sleep(1);
        }
        //6.关闭生产者producer
        producer.shutdown();
    }

}
